<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\prepay\gateway;

use addons\epay\library\Service;
use app\common\library\WechatPay;
use app\common\manager\OrderManager;
use app\common\manager\PayLogManager;
use app\common\model\RechargeOrder;
use app\common\model\Transferrecord;
use think\Db;
use think\Exception;

class Transfer
{
    CONST METHOD = 'Transfer';

    CONST TYPE_ALIPAY = 1;
    CONST TYPE_WECHAT = 2;
    public function order($user,$request,$trans=true)
    {
        if ($trans)
            Db::startTrans();
        try {
            $prePayment = null;
            $type = $request['type'] ?? 'wechat';
            $orderId = orderNum();
            if (empty($request['transfer_detail_list']) || !is_array($request['transfer_detail_list'])) {
                throw new Exception('当前数据格式有误或为空');
            }

            $transferOrder = [];
            foreach ($request['transfer_detail_list'] as $item) {
                $transferOrder[] = [
                    'user_id'=>$item['user_id'],
                    'open_id'=>$item['openid'],
                    'type'=>$type,
                    'order'=>$item['out_detail_no'],
                    'amount'=>bcdiv($item['transfer_amount'],100,2),
                    'relation_id'=>$item['relation_id'] ?? 0,
                    'batch_no'=>$request['out_batch_no'],
                    'detail_no'=>$item['out_detail_no'],
                    'status'=> Transferrecord::STATUS_SEND,
                    'detail'=> $request['detail'] ?? 0,
                    'relation_order'=>$item['relation_order'] ?? '',
                ];

            }

            if (empty($transferOrder)){
                throw new Exception('发放失败');
            }

            $transferModel = new Transferrecord();
            if(!$transferModel->insertAll($transferOrder)){
                throw new Exception('转账记录插入失败');
            }

            $result1 = PayLogManager::record(['user_id'=>0,'method'=>self::METHOD,'type'=> $type=='alipay' ? self::TYPE_ALIPAY : self::TYPE_WECHAT,'order'=>$orderId,'money'=>$request['total_amount'],'request'=>serialize($request),'create_time'=>time()],false);

            if ($result1['code'] == PayLogManager::$successCode) {
                $wechatPay = new WechatPay();
                foreach ($request['transfer_detail_list'] as &$item) {
                    unset($item['relation_id'],$item['relation_order'],$item['user_id']);
                }

                if (isset($request['relationType'])){
                    unset($request['relationType']);
                }

                if (isset($request['detail'])){
                    unset($request['detail']);
                }

                $response = $wechatPay->transfer($request);
                if ($response['code'] != $wechatPay->successCode) {
                    throw new Exception($response['message']);
                }
                if ($trans)
                    Db::commit();
            }else{
                throw new Exception($result1['message']);
            }
            return ['code'=>1,'message'=>'success','data'=>[]];
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage(),'data'=>null];
        }
    }
}